#!/bin/bash

set -e

# 颜色输出函数
print_info() {
    echo -e "\033[1;34m[INFO]\033[0m $1"
}

print_success() {
    echo -e "\033[1;32m[SUCCESS]\033[0m $1"
}

print_error() {
    echo -e "\033[1;31m[ERROR]\033[0m $1"
}

print_info "🚀 启动Work Publish System..."

# 等待数据库连接
print_info "⏳ 等待数据库连接..."
max_attempts=30
attempt=1

while [ $attempt -le $max_attempts ]; do
    if node -e "
        const { Pool } = require('pg');
        const pool = new Pool({
            host: process.env.DB_HOST || 'postgres',
            port: process.env.DB_PORT || 5432,
            database: process.env.DB_DATABASE || 'postgres',
            user: process.env.DB_USERNAME || 'postgres',
            password: process.env.DB_PASSWORD || 'difyai123456'
        });
        pool.query('SELECT 1').then(() => {
            console.log('数据库连接成功');
            process.exit(0);
        }).catch(err => {
            console.error('数据库连接失败:', err.message);
            process.exit(1);
        });
    " 2>/dev/null; then
        print_success "✅ 数据库连接成功"
        break
    else
        print_info "🔄 数据库连接失败，重试 ($attempt/$max_attempts)..."
        sleep 2
        attempt=$((attempt + 1))
    fi
done

if [ $attempt -gt $max_attempts ]; then
    print_error "❌ 数据库连接超时，退出"
    exit 1
fi

# 初始化数据库（如果需要）
if [ "$INIT_DB" = "true" ] || [ ! -f "/app/.db_initialized" ]; then
    print_info "🔧 初始化数据库..."
    if node scripts/initDatabase.js; then
        print_success "✅ 数据库初始化成功"
        touch /app/.db_initialized
    else
        print_error "❌ 数据库初始化失败"
        exit 1
    fi
fi

# 确保uploads目录存在
mkdir -p /app/uploads
chmod 755 /app/uploads

# 安装serve（如果不存在）
if ! command -v serve > /dev/null 2>&1; then
    print_info "📦 安装serve..."
    npm install -g serve
fi

# 启动后端服务器
print_info "🔧 启动后端API服务器 (端口: ${BACKEND_PORT:-9091})..."
node server/app.js &
BACKEND_PID=$!

# 等待后端启动
sleep 3

# 检查后端是否启动成功
if kill -0 $BACKEND_PID 2>/dev/null; then
    print_success "✅ 后端服务器启动成功 (PID: $BACKEND_PID)"
else
    print_error "❌ 后端服务器启动失败"
    exit 1
fi

# 启动前端服务器
print_info "🌐 启动前端服务器 (端口: ${PORT:-9090})..."
serve -s build -l ${PORT:-9090} &
FRONTEND_PID=$!

# 等待前端启动
sleep 2

# 检查前端是否启动成功
if kill -0 $FRONTEND_PID 2>/dev/null; then
    print_success "✅ 前端服务器启动成功 (PID: $FRONTEND_PID)"
else
    print_error "❌ 前端服务器启动失败"
    exit 1
fi

print_success "🎉 Work Publish System 启动完成!"
print_info "📍 前端地址: http://211.86.197.10:${PORT:-9090}"
print_info "🔌 API地址: http://211.86.197.10:${BACKEND_PORT:-9091}/api"
print_info "📊 健康检查: http://211.86.197.10:${BACKEND_PORT:-9091}/api/health"

# 优雅关闭处理
cleanup() {
    print_info "🛑 正在关闭服务..."
    kill $BACKEND_PID $FRONTEND_PID 2>/dev/null || true
    wait $BACKEND_PID $FRONTEND_PID 2>/dev/null || true
    print_success "✅ 服务已关闭"
    exit 0
}

trap cleanup SIGTERM SIGINT

# 等待所有后台进程
wait